<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------

namespace app\Api\controller;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use Aliyun\Core\Config;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Core\Profile\DefaultProfile;
use app\common\controller\Api;
use app\common\model\Dept;
use think\Db;
use think\Session;

Config::load();
class User extends Api {


    public function sendRegCode(){
        $accessKeyId = 'LTAI8LXcKo56jPdF'; //阿里云申请的 Access Key ID
        $accessKeySecret = 'avQvAlsX6gilVY8p24B4j5QrHkx8bd'; //阿里云申请的 Access Key Secret

        // 短信API产品名
        $product = "Dysmsapi";

        // 短信API产品域名
        $domain = "dysmsapi.aliyuncs.com";

        // 暂时不支持多Region
        $region = "cn-hangzhou";

        // 服务结点
        $endPointName = "cn-hangzhou";

        // 初始化用户Profile实例
        $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);

        // 增加服务结点
        DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);

        // 初始化AcsClient用于发起请求
        $this->acsClient = new DefaultAcsClient($profile);


        $code = rand(1000,9999);
        Session::set('code',$code);
        $result = file_get_contents('php://input');
        if($result){

            $data = json_decode($result, true);
            $phone = $data['phone'];
        }else{
            $phone = $_GET['phone'];
        }
        $req_data = array();

        $org = Db::table('organization')->where('phone', $phone)->find();
        if($org){
            $req_data['code'] = 199;
            echo json_encode($req_data);
            die(0);
        }

        $ret = $this->send_sms($phone,$code);
        if($ret == 'OK'){
            $req_data['code'] = 200;
        }else{
            $req_data['code'] = 100;
        }
        echo json_encode($req_data);
    }

    public function sendCode(){
        $accessKeyId = 'LTAI8LXcKo56jPdF'; //阿里云申请的 Access Key ID
        $accessKeySecret = 'avQvAlsX6gilVY8p24B4j5QrHkx8bd'; //阿里云申请的 Access Key Secret

        // 短信API产品名
        $product = "Dysmsapi";

        // 短信API产品域名
        $domain = "dysmsapi.aliyuncs.com";

        // 暂时不支持多Region
        $region = "cn-hangzhou";

        // 服务结点
        $endPointName = "cn-hangzhou";

        // 初始化用户Profile实例
        $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);

        // 增加服务结点
        DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);

        // 初始化AcsClient用于发起请求
        $this->acsClient = new DefaultAcsClient($profile);


        $code = rand(1000,9999);
        Session::set('code',$code);
        $result = file_get_contents('php://input');
        if($result){

            $data = json_decode($result, true);
            $phone = $data['phone'];
        }else{
            $phone = $_GET['phone'];
        }


        $ret = $this->send_sms($phone,$code);
        $req_data = array();
        if($ret == 'OK'){
            $req_data['code'] = 200;
        }else{
            $req_data['code'] = 100;
        }
        $req_data['code'] = 200;

        echo json_encode($req_data);
    }

    public function sendSms($signName, $templateCode, $phoneNumbers, $templateParam = null, $outId = null) {

        // 初始化SendSmsRequest实例用于设置发送短信的参数
        $request = new SendSmsRequest();

        // 必填，设置雉短信接收号码
        $request->setPhoneNumbers($phoneNumbers);

        // 必填，设置签名名称
        $request->setSignName($signName);

        // 必填，设置模板CODE
        $request->setTemplateCode($templateCode);

        // 可选，设置模板参数
        if($templateParam) {
            $request->setTemplateParam(json_encode($templateParam));
        }

        // 可选，设置流水号
        if($outId) {
            $request->setOutId($outId);
        }

        // 发起访问请求
        $acsResponse = $this->acsClient->getAcsResponse($request);

        // 打印请求结果
        // var_dump($acsResponse);

        return $acsResponse;

    }

    public function send_sms($phone,$code){

        $response = $this->sendSms(
            "湖南普卓信息科技有限公司", // 短信签名
            "SMS_102470122", // 短信模板编号
            $phone, // 短信接收者
            Array(  // 短信模板中字段的值
                "code"=>$code,
            ),
            ""
        );
        return $response->Code;
    }

    public function verfyCode(){

        $code = Session::get('code');
        $result = file_get_contents('php://input');
        $data = json_decode($result, true);
        $req_data = array();
        if($data['code'] == $code){
            Session::delete('code');
            $req_data['code'] = 200;
        }else{
            $req_data['code'] = 100;
        }
        echo  json_encode($req_data);
    }

    public function getUserInfoByToken(){
        $result = file_get_contents('php://input');
        $data = json_decode($result, true);
        $token = $data['token'];
        $connect_uid = $data['connect_uid'];

        $uinfo =  Db::table('users')->where('rongCloudToken',$token)->find();

        $req_data = array();
        if($uinfo){

            if($uinfo['connect_uid'] == ''){
                Db::table('users')->where('id',$uinfo['id'])->update(['connect_uid' => $connect_uid]);

            }

            $req_data['code'] = 200;
            $back_data = array();
            $phone = $uinfo['phone'];
            $org_id = '';
            $dept_id = '';
            $dept_name = '';
            $org_name = '';

            if($uinfo['org_id'] == ''){

                $tmp =  Db::table('tmp_users')->where('phone',$phone)->find();
                if($tmp){

                    $org_id = $tmp['org_id'];
                    $org =  Db::table('organization')->where('id',$org_id)->find();
                    if($org){
                        $org_name = $org['name'];
                    }

                    $dept =  Db::table('dept')->where('name',$tmp['dept_name'])->where('org_id',$org_id)->find();
                    if($dept){
                       Db::table('dept')->where('id',$dept['id'])->setInc('nums');
                       $dept_id = $dept['id'];
                        $dept_name = $dept['name'];
                        error_log("=========tmp detpid =======".$dept_id."======org id=====".$org_id);
                       Db::table('users')->where('rongCloudToken',$token)->update(['org_id' => $org_id,'dept_id'=>$dept_id]);

                    }else{
                        $org_id = '';
                    }
                    Db::table('tmp_users')->where('phone',$phone)->delete();
                }

            }else{
                $org_id = $uinfo['org_id'];
                $dept_id = $uinfo['dept_id'];
                $org =  Db::table('organization')->where('id',$org_id)->find();
                $dept =  Db::table('dept')->where('id',$dept_id)->find();
                $dept_name = $dept['name'];
                $org_name = $org['name'];
            }

            $back_data['id'] = $uinfo['id'];
            $back_data['nickname'] = $uinfo['nickname'];
            $back_data['portraitUri'] = $uinfo['portraitUri'];
            $back_data['org_id'] = $org_id;
            $back_data['dept_id'] = $dept_id;
            $back_data['email'] = $uinfo['email'];
            $back_data['org_name'] = $org_name;
            $back_data['dept_name'] = $dept_name;
            $req_data['result'] = $back_data;



        }else{
            $req_data['code'] = 100;

        }
        echo json_encode($req_data);

    }

    public function deptList(){
        $dept = new Dept();
        $result = file_get_contents('php://input');
        $data = json_decode($result, true);
        $orgId = $data['org_id'];
        $list = $dept->getDeptList($orgId);

        $req_data = array();
        $back_data = array();
        $req_data['code'] = 200;
        $back_data['dept'] = $list;
        $req_data['result'] = $back_data;

        echo json_encode($req_data);
    }

    public function updateUserInfo(){
        $result = file_get_contents('php://input');
        $data = json_decode($result, true);
        $org_id = $data['org_id'];
        $dept_id = $data['dept_id'];
        $token = $data['token'];
        Db::table('users')->where('rongCloudToken', $token)->update(['org_id' => $org_id,'dept_id'=>$dept_id]);
        Db::table('dept')->where('id', $dept_id)->setInc('nums');

        $req_data = array();
        $req_data['code'] = 200;
        echo json_encode($req_data);


    }

    public function getOrgMemberList(){
        $result = file_get_contents('php://input');
        $data = json_decode($result, true);
        $org_id = $data['org_id'];

        $list =  Db::table('dept')->where('org_id', $org_id)->select();
        foreach ($list as $key=> $val){
            $users = Db::table('users')->where('dept_id', $val['id'])->select();
            $list[$key]['users'] = $users;
        }

        echo json_encode($list);

    }

    public function updateEmail(){

        $result = file_get_contents('php://input');
        $data = json_decode($result, true);
        $email = $data['email'];
        $token = $data['token'];
        Db::table('users')->where('rongCloudToken', $token)->update(['email' => $email]);
        $req_data = array();
        $req_data['code'] = 200;
        echo json_encode($req_data);
    }

    public function  deptMemberList(){

        $result = file_get_contents('php://input');
        $data = json_decode($result, true);
        $deptId = $data['org_id'];
        $list = Db::table('users')->where('dept_id', $deptId)->select();
        $req_data = array();
        $back_data = array();
        $req_data['code'] = 200;
        $back_data['users'] = $list;
        $req_data['result'] = $back_data;
        echo  json_encode($req_data);
    }

    public function add_meet(){
        $result = file_get_contents('php://input');
        $data = json_decode($result, true);
        $name = $data['name'];
        $zt = $data['zt'];
        $address = $data['address'];
        $meet_time = $data['time'];
        $token = $data['token'];
        $user = Db::table('users')->where('rongCloudToken', $token)->find();
        $mList = $data['list'];
        $org_id = $user['org_id'];

        $time = strtotime($meet_time);
        $id = Db::table('meet')->insert(['name' => $name,'zt'=>$zt,'address'=>$address,'org_id'=>$org_id,'meet_time'=>$time]);
        $user_array = array();
        $user_data = array();

        foreach ($mList as $key=> $val){
            $uid = $val['uid'];
            $user_data[$key] = $uid;

            if($uid == $user['connect_uid']){
                $user_array[$key]['is_creator'] = 1;
            }else{
                $user_array[$key]['is_creator'] = -1;

            }
            $user_array[$key]['uid'] = $val['uid'];
            $user_array[$key]['mid'] = $id;
        }
        Db::table('meet_user')->insertAll($user_array);
        $url = "https://api.cn.ronghub.com/push.json";
        //$data = {"platform":["ios","android"],"audience":{"userid":["123","456"]},"notification":{"alert":"this is a push"}}
        $data = array();
        $platform_data = array();
        $platform_data[0] = "ios";
        $platform_data[1] = "android";
        $audience_data = array();

        $content_data = array();
        $content_data['type'] = "meet";
        $content_data['content'] = $id;

        $audience_data['userid'] = $user_data;
        $notification_data = array();
        $notification_data['alert'] = json_encode($content_data);
        $data['platform'] = $platform_data;
        $data['audience'] = $audience_data;
        $data['notification'] = $notification_data;
//
//        echo json_encode($data);
//        die(0);

        $result = $this->http_post_json($url,json_encode($data));
        $req_data = array();
        $req_data['code'] = 200;

        echo json_encode($req_data);
    }

    function http_post_json($url, $jsonStr)
    {

        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1('2hVZ4EhoXdep'.$nonce.$timeStamp);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: Application/json',
                'Content-Length: ' . strlen($jsonStr),
                'RC-Nonce:'.$nonce,
                'RC-Timestamp:'.$timeStamp,
                'RC-Signature:'.$sign,
                'RC-App-Key:'.'vnroth0kv4oco',
            )
        );
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return array($httpCode, $response);
    }


    public function meet_list(){

        $result = file_get_contents('php://input');
        $data = json_decode($result, true);

        $token = $data['token'];
        $user = Db::table('users')->where('rongCloudToken', $token)->find();
        $time = time();
        $list = Db::table('meet')->where('org_id', $user['org_id'])->where('meet_time','>',$time)->select();
        foreach ($list as $key => $val){
            $list[$key]['meet_time'] =date("Y-m-d H:i",$val['meet_time']);
            $one  = Db::table('meet_user')->where('uid', $user['connect_uid'])->find();
            if($one){

                $record = Db::table('meet_user_record')->where('uid', $user['connect_uid'])->where('mid',$val['id'])->find();
                if($record){
                    if($record['type'] == 1){
                        $list[$key]['is_do'] = 1;
                    }else{
                        $list[$key]['is_do'] = 2;

                    }
                }else{
                    $list[$key]['is_do'] = 0;

                }
            }else{
                $list[$key]['is_do'] = -1;
            }

        }
        echo json_encode($list);

    }

    public function meet_user_list(){
        $result = file_get_contents('php://input');
        $data = json_decode($result, true);
        $id = $data['token'];
        $list = Db::table('meet_user')->where('mid',$id)->select();
        foreach ($list as $key=> $val){
            $user = Db::table('users')->where('connect_uid', $val['uid'])->find();
            $list[$key]['name'] = $user['nickname'];
            $dept = Db::table('dept')->where('id', $user['dept_id'])->find();
            $list[$key]['deptName'] = $dept['name'];


            $record = Db::table('meet_user_record')->where('uid', $val['uid'])->where('mid',$val['mid'])->find();
            $reason = "";
            if($record){
                if($record['type'] == 1){
                    $list[$key]['is_do'] = 1;
                    $reason = $record['mark'];
                }else{
                    $list[$key]['is_do'] = 2;

                }
            }else{
                $list[$key]['is_do'] = -1;

            }
            $list[$key]['mark'] = $reason;

        }
        echo json_encode($list);

    }

    public function meet_do_record(){
        $result = file_get_contents('php://input');
        $data = json_decode($result, true);
        $mid = $data['mid'];
        $uid = $data['uid'];
        $type = $data['type'];
        $mark = $data['mark'];
        $time = time();
        $id = Db::table('meet_user_record')->insert(['uid' => $uid,'mid'=>$mid,'add_time'=>$time,'type'=>$type,'mark'=>$mark]);
        echo "200";

    }




	public function login(){
		//$this->data['code'] = 1;
		return $this->data;
	}

	public function getuser(\think\Request $request){
		$this->data['code'] = 1;
		$this->data['data'] = db('Member')->where('uid', $request->param('uid'))->find();
		return $this->data;
	}



	public function getMeet(){

        $result = file_get_contents('php://input');
        $data = json_decode($result, true);
        $id = $data['mid'];
        $meet = Db::table('meet')->where('id', $id)->find();
        $token = $data['uid'];
        $user = Db::table('users')->where('rongCloudToken', $token)->find();
        if($meet){
            $meet['time'] = date("Y-m-d H:i",$meet['meet_time']);

            $one  = Db::table('meet_user')->where('uid', $user['connect_uid'])->find();
            if($one){

                $record = Db::table('meet_user_record')->where('uid', $user['connect_uid'])->where('mid',$meet['id'])->find();
                if($record){
                    if($record['type'] == 1){
                        $meet['is_do'] = 1;
                    }else{
                        $meet['is_do'] = 2;

                    }
                }else{
                    $meet['is_do'] = 0;

                }
            }else{
                $meet['is_do'] = -1;
            }
        }

        echo json_encode($meet);

    }





}